﻿using System;
using System.Collections;
using System.Runtime.CompilerServices;
using QGMiniGame;
using UnityEngine;
using UnityEngine.Networking;

public class AdManager : MonoBehaviour
{
    public static bool TestMode = false;

    public static string Owner = "著作权人：厦门歆阳网络科技有限公司"; //健康忠告-著作权人
    public static string License = "登记号：2024SA0084418"; //健康忠告v-登记号
    public static int AgeLimit = 12; //健康忠告-适龄 8 12 16

    public static string Company = "杭州电鳐网络科技有限公司"; //隐私-公司
    public static string Email = "客服邮箱：1322555335@qq.com"; //隐私-联系方式

    public static int Year = 2024;
    public static int Month = 5;
    public static int Day = 15;
    public static int Hour = 18;

    private static string AppId = "105712532";
    private static string VideoId = "a26e964204f74d318fc5982ab7b364ea";
    private static string CustomId = "cfb7a1c5e1404f0797b7176e02e1634e";
    private static string BannerId = "cb7101671e2a4419968efccd6078d56b";


    static AdManager _instance;
    public static AdManager Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject gameObject = new GameObject("AdManager");
                _instance = gameObject.AddComponent<AdManager>();
                DontDestroyOnLoad(gameObject);
            }
            return _instance;
        }

    }

    public bool ZiTanIsBeGin = false;//是否开启自弹
    //自弹
    public void NativeZiTan(int time)
    {
        Invoke("NativeZiTan", time);
    }

    public void ShowBanner()
    {
        if (TestMode) return;
#if UNITY_EDITOR

#elif UNITY_ANDROID
#else
        ShowQGBanner();
#endif
    }

    public void ShowNative()
    {
        Debug.Log("弹出原生广告");
        if (TestMode) return;
#if UNITY_EDITOR

#elif UNITY_ANDROID
#else
        ShowQGNative();
#endif
    }

    public void ShowVideo(Action action)
    {
        Debug.Log("弹出视频广告");
        if (TestMode)
        {
            action?.Invoke();
            return;
        }
#if UNITY_EDITOR
        action?.Invoke();
        return;
#elif UNITY_ANDROID
#else
        ShowQGVideo(action);
#endif
    }

    public static void Quit()
    {
#if UNITY_EDITOR
        //GameManager.Instance.Quit();
#elif UNITY_ANDROID
#else
        QGMiniGameManager.Instance.Quit();
#endif
    }

    #region Android

    private static AndroidJavaClass jc;
    private static AndroidJavaObject jo;

    private static void CheckNull()
    {
        if (jc == null || jo == null)
        {
            jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        }
    }

    private static void ShowAndroidBanner()
    {
        CheckNull();
        jo.Call("ShowBanner");
    }

    private static void ShowAndroidNative()
    {
        CheckNull();
        jo.Call("ChaPing");
    }

    private static void ShowAndroidVideo(Action action)
    {
        jo.Call("GameVideo1", action);
    }

    private static void ShowAndroidKeFu() => jo.Call("KeFu");

    private static void ShowAndroidMoreGame() => jo.Call("MoreGame");

    private static void ShowAndroidPrivacy() => jo.Call("Hide");

    private static void AndroidQuitGame() => jo.Call("Quit");

    #endregion

    #region VIVO

    /// <summary>Banner 广告</summary>
    private static void ShowQGBanner()
    {
        if (InTimeRange(Year, Month, Day, Hour)) return;

        var bannerAd = QG.CreateBannerAd(new QGCreateBannerAdParam
        { adIntervals = 30, posId = BannerId });

        bannerAd.OnLoad(() =>
        {
            bannerAd.Show(
                (msg) => { Debug.Log("QG.bannerAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.bannerAd.Show fail = " + msg.errMsg); }
            );
        });
        bannerAd.OnError((QGBaseResponse msg) =>
        {
            Debug.Log("QG.bannerAd.OnError success = " + JsonUtility.ToJson(msg));
        });
    }

    /// <summary>原生广告</summary>
    public void ShowQGNative()
    {
        if (InTimeRange(Year, Month, Day, Hour)) return;
        Invoke("Native", 1);
    }

    void Native()
    {
        var customAd = QG.CreateCustomAd(new QGCreateCustomAdParam()
        {
            posId = CustomId,
            style = new Style()
            {
                left = Screen.width / 2 + 250,
                top = Screen.height / 2
            }
        });
        customAd.OnLoad(() =>
        {
            Debug.Log("QG.customAd.OnLoad success = ");
            customAd.Show(
                (msg) => { Debug.Log("QG.customAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.customAd.Show fail = " + msg.errMsg); }
            );
        });
        customAd.OnError((QGBaseResponse msg) =>
        {
            Debug.Log("QG.customAd.OnError success = " + JsonUtility.ToJson(msg));
        });
        customAd.OnHide(() => { Debug.Log("QG.customAd.OnHide success "); });
    }

    /// <summary>视频广告</summary>
    public void ShowQGVideo(Action action)
    {
        var rewardedVideoAd = QG.CreateRewardedVideoAd(new QGCommonAdParam { posId = VideoId });

        rewardedVideoAd.OnLoad(() =>
        {
            rewardedVideoAd.Show(
                (msg) => { Debug.Log("QG.rewardedVideoAd.Show success = " + JsonUtility.ToJson(msg)); },
                (msg) => { Debug.Log("QG.rewardedVideoAd.Show fail = " + msg.errMsg); }
            );
        });
        rewardedVideoAd.OnError((QGBaseResponse msg) =>
        {
            // Tip.Show("视频广告加载失败");
            Debug.Log("QG.rewardedVideoAd.OnError success = " + JsonUtility.ToJson(msg));
        });
        rewardedVideoAd.OnClose((QGRewardedVideoResponse msg) =>
        {
            if (msg.isEnded)
            {
                action?.Invoke();
                Debug.Log("QG.rewardedVideoAd.OnClose success = " + " 播放成功");
            }
            if (ShieldAddress) ShowNative();
        });
    }

    public static bool InTimeRange(int year, int month, int day, int hour, int minute = 0, int second = 0) => DateTime.Now < new DateTime(year, month, day, hour, minute, second);


    #endregion

    // #region OPPO

    // /// <summary>Banner 广告</summary>
    // private static void ShowQGBanner()
    // {
    //     if (ZTool.InTimeRange(Year, Month, Day, Hour)) return;

    //     var bannerAd = QG.CreateBannerAd(new QGCreateBannerAdParam()
    //     {
    //         adUnitId = BannerId
    //     });
    //     Debug.Log("创建Banner广告开始运行");
    //     bannerAd.OnLoad(() => { Debug.Log("banner广告加载成功"); });
    //     bannerAd.OnError((QGBaseResponse msg) => { Debug.Log("QG.bannerAd.OnError success = " + JsonUtility.ToJson(msg)); });
    // }

    // /// <summary>原生广告</summary>
    // public void ShowQGNative()
    // {
    //     if (ZTool.InTimeRange(Year, Month, Day, Hour)) return;
    //     Invoke("Native", 1);
    // }

    // void Native()
    // {
    //     var customAd = QG.CreateCustomAd(new QGCreateCustomAdParam()
    //     {
    //         adUnitId = CustomId //上文下图
    //     });
    //     Debug.Log("创建原生模板广告开始运行");
    //     customAd.OnLoad(() => { Debug.Log("原生模板广告加载成功"); });
    //     customAd.Show(
    //         (msg) => { Debug.Log("原生模板广告展示成功 = " + JsonUtility.ToJson(msg)); },
    //         (msg) => { Debug.Log("原生模板广告展示失败 = " + msg.errMsg); }
    //     );
    //     customAd.OnError((QGBaseResponse msg) => { Debug.Log("QG.customAd.OnError success = " + JsonUtility.ToJson(msg)); });
    //     customAd.OnHide(() => { Debug.Log("QG.customAd.OnHide success "); });
    // }



    // /// <summary>视频广告</summary>
    // public void ShowQGVideo(Action action)
    // {
    //     var rewardedVideoAd = QG.CreateRewardedVideoAd(new QGCommonAdParam()
    //     {
    //         adUnitId = VideoId
    //     });
    //     Debug.Log("创建激励视频开始运行");
    //     rewardedVideoAd.OnLoad(() =>
    //     {
    //         Debug.Log("激励视频广告加载成功");
    //         rewardedVideoAd.Show();
    //     });
    //     rewardedVideoAd.OnError((QGBaseResponse msg) => { 
    //         Debug.Log("QG.rewardedVideoAd.OnError success = " + JsonUtility.ToJson(msg));
    //         Tip.Show("视频广告加载失败");
    //     });
    //     rewardedVideoAd.OnClose((QGRewardedVideoResponse msg) =>
    //     {
    //         if (msg.isEnded)
    //         {
    //             action?.Invoke();
    //             Debug.Log("激励视频广告完成，发放奖励");
    //         }
    //         else
    //         {
    //             Debug.Log("激励视频广告取消关闭，不发放奖励");
    //         }
    //         if (!AdManager1.instance.ShieldAddress) ShowNative();
    //     });
    // }

    // #endregion

    /// <summary>
    /// 是否是屏蔽区域—默认被屏蔽，白包
    /// </summary>
    public bool ShieldAddress = true;
    //获取的json数据
    private string GetjsonText;
    public bool isInit = false;
    //屏蔽区域 "厦门市",
    string[] PinBiAddress = new string[] {"厦门市","石家庄", "太原市", "沈阳市", "长春市", "哈尔滨市", "南京市", "杭州市", "合肥市",
                            "福州市", "南昌市", "济南市", "郑州市", "长沙市", "武汉市", "海口市", "成都市", "贵阳市", "昆明市",
                            "西安市", "兰州市", "西宁市", "北京市", "天津市", "上海市", "重庆市", "大连市", "青岛市", "广东省" };


    /// <summary>
    /// 实例化黑白包
    /// </summary>
    public void InitData()
    {
        // ShieldAddress = ZTool.InShieldTime();
        StartCoroutine(GetUrlText());
        if (isInit) return;
        //InvokeRepeating("ShowYuanSheng", 30, 30);
    }

    IEnumerator GetUrlText()
    {
        UnityWebRequest request = UnityWebRequest.Get("https://yxapi.tomatojoy.cn/getIp");
        request.timeout = 2;//超时时间
        yield return request.SendWebRequest();
        try
        {
            //是否下载完成
            if (request.isDone)
            {
                if (request.isHttpError || request.isNetworkError)
                {
                    //    Debug.Log("下载失败"+request.error);
                    ShieldAddress = true;
                }
                else
                {
                    GetjsonText = request.downloadHandler.text;
                    Debug.Log("下载成功！！" + GetjsonText);
                    JsonData jsdata = JsonUtility.FromJson<JsonData>(GetjsonText);
                    Debug.Log("当前城市" + jsdata.data.city);
                    for (int i = 0; i < PinBiAddress.Length; i++)
                    {
                        if (jsdata.data.province == "广东省")
                        {
                            break;
                        }
                        if (jsdata.data.city == PinBiAddress[i])
                        {
                            // Debug.Log("当前处于屏蔽区域内");
                            ShieldAddress = true;
                            break;
                        }
                        else
                        {
                            ShieldAddress = false;
                        }
                    }
                }
            }
            Debug.Log("当前是否白包" + ShieldAddress);
        }
        catch (System.Exception)
        {
            Debug.Log("加载失败");
            throw;
        }
    }
    IEnumerator YuanSheng()
    {
        Debug.Log("执行");
        if (!ShieldAddress)
        {
            if (ShieldAddress) AdManager.Instance.ShowNative();
        }
        yield return 30;
    }
    void ShowYuanSheng()
    {
        Debug.Log("执行");
        if (!ShieldAddress)
        {
            isInit = true;
            if (ShieldAddress) AdManager.Instance.ShowNative();
            AdManager.Instance.ShowBanner();
        }
    }
}

[System.Serializable]
class data
{
    public string country;     //国家
    public string province;    //省份
    public string city;        //城市
    public string ip;          //ip
    public string server_time; //服务器时间
}
[System.Serializable]
class JsonData
{
    public string code;
    public data data;
}
